//
//  TLVideoCell.m
//  FunnyVideo
//
//  Created by 李鑫 on 15/8/19.
//  Copyright © 2015年 NewEggTech. All rights reserved.
//

#import "TLVideoCell.h"

#import "TLVCmtThumbCell.h"

#import "AVOSManger.h"

#import "TLShareCenter.h"


@interface TLVideoCell ()

@property (nonatomic,strong) TLVCmtThumbCell *curThumbCell;
@end

@implementation TLVideoCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(nullable NSString *)reuseIdentifier{
 
    
    return [super initWithStyle:style reuseIdentifier:reuseIdentifier];
}

- (void)awakeFromNib {
    NSLog(@"%s",__PRETTY_FUNCTION__);
}

- (void)drawRect:(CGRect)rect{
    
      // self.videoPreviewThumb.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    CGFloat width = CGRectGetWidth(self.cellBackgroundView.frame) * 0.95;
    
    self.VideoLayerWc.constant = width;
    
    self.VCmtTLayerWc.constant = width;
    
    //self.cellCmtThumbTable.constant = self.commentThumbTable.contentSize.height;
    
//    self.cellBackgroundView.layer.shadowColor = [UIColor blackColor].CGColor;
//    self.cellBackgroundView.layer.shadowOffset = CGSizeMake(0.6, -1);
//    self.cellBackgroundView.layer.shadowOpacity = 0.5;
    
    self.videoPreviewThumb.clipsToBounds = YES;
    self.videoPreviewThumb.contentMode = UIViewContentModeScaleAspectFill;
    
    [self storkeVideoPlayerBorderPlayerWidth:width];
    
    
    [[self videoPlayer] addPlayerEventCallBack:^(TLVideoPlayerEventType eventType, float value) {
        NSLog(@"Video Event Call back");
        switch (eventType) {
            case TLVideoPlayerEventPlay:
            {
                if([self.delegate respondsToSelector:@selector(videoPlay:)])
                {
                    [self.delegate videoPlay:[self videoPlayer]];
                }
            }
                break;
            case TLVideoPlayerEventPause:
            {
                if([self.delegate respondsToSelector:@selector(videoPaused:)])
                {
                    [self.delegate videoPaused:[self videoPlayer]];
                }
            }
            case TLVideoPlayerEventFastForward:
            {
                if([self.delegate respondsToSelector:@selector(videoFastForward:)])
                {
                    [self.delegate videoFastForward:[self videoPlayer]];
                }
            }
            case TLVideoPlayerEventRewindForward:
            {
                if([self.delegate respondsToSelector:@selector(videoFastReward:)])
                {
                    [self.delegate videoFastReward:[self videoPlayer]];
                }
            }
                case TLVideoPlayerEventTypeValueChanged:
                {
                    //Update Progress
                    [self updateProgress:value];
                }
            default:
                break;
        }
    }];
}

- (void)toggleCommentMode:(BOOL)istoggle{
    self.separationLine.hidden = !istoggle;
    [self.cmtButton setSelected:istoggle];
}

- (void)storkeVideoPlayerBorderPlayerWidth:(CGFloat)width{
    UIImageView *storkeIV = [[UIImageView alloc] initWithFrame:CGRectMake(0.05*self.cellBackgroundView.frame.origin.x+5, self.videoPreviewThumb.frame.origin.y - 3, width+7, self.videoPreviewThumb.frame.size.height+5)];
    [storkeIV setImage:[UIImage imageNamed:@"playerStorke"]];
    [self.cellBackgroundView addSubview:storkeIV];
    [self.cellBackgroundView sendSubviewToBack:storkeIV];
}

#pragma mark -- Button Actions
- (IBAction)pushCmtView:(id)sender{
    if([self.delegate respondsToSelector:@selector(videoWillShowComment:cell:)])
    {
        [self.delegate videoWillShowComment:self.videoPlayer.v_id cell:self];
    }
}

/*
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    // Configure the view for the selected state
    //NSLog(@"Cell Click");
}
 */

- (void)updateProgress:(float)pg{
    self.videoProgress.progress = pg;
}

- (TLVideoPlayer *)videoPlayer{
    return (TLVideoPlayer*)[[self contentView] viewWithTag:100];
}

- (void)setVideoAssestURL:(NSURL *)url{
    self.videoPlayer.url = url;
}

- (void)setVideoID:(NSString *)v_id{
    [[AVOSManger sharedManger] queryVideoIdByObjectId:v_id completion:^(NSString *objectId) {
        self.videoPlayer.v_id = objectId;
        //update the likes count
        [[AVOSManger sharedManger] getSupportAtVideoId:objectId completion:^(NSUInteger sptNum) {
            self.supportLabel.text = [NSString stringWithFormat:@"%ld",sptNum];
        } isLiked:^(BOOL isLiked,BOOL canLike) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    if(isLiked)
                    {
                        [self.supportButton setOn:YES];
                        [self.supportButton setEnabled:YES];
                    }
                    
                    if(!canLike)
                    {
                        [self.supportButton setEnabled:NO];
                    }
                });
           }];
    }];
}

- (void)resetPlayer{
    [self.videoPlayer reset];
}

#pragma mark -- Support Button Click
- (IBAction)supportButtonClick:(TLGifAniButton *)sender{
    [self setSupported:sender.on];
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(nonnull UITableView *)tableView estimatedHeightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    return 180.f;
}

- (CGFloat)tableView:(nonnull UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    TLVCmtThumbCell *currentCell = self.curThumbCell;
    
    currentCell.commentTV.text = @"Big baba lala niubi 的 多哈手机壳n";
    
    CGSize fitSize = [self.curThumbCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    CGFloat tWidth = self.curThumbCell.commentTV.frame.size.width;
    
    CGSize tSize = [self.curThumbCell.commentTV sizeThatFits:TFIL_MAX(tWidth)];
    
    NSLog(@"Fit Size for current cell %@",NSStringFromCGSize(fitSize));
    
    float height = fitSize.height + tSize.height;
    //  Adapt For iOS8&7
    //  if([TLDeviceManger osVersionOlderOrEqualTo:8.0])
    //  return UITableViewAutomaticDimension;
    //  else
    return height + 1;
}

#pragma mark -- UITableViewDataSource For User Comment Thumb TableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}

- (UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    //dequeue reuse
    TLVCmtThumbCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TLVCThumbCell"];
    
    if(!cell)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TLVCmtThumbCell" owner:self options:nil];
        if ([nib count]>0)
        {
            cell = [nib objectAtIndex:0];
        }
    }
    
    self.curThumbCell = cell;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

#pragma mark -- UITableViewDelegate 
- (void)tableView:(nonnull UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    NSLog(@"%s",__PRETTY_FUNCTION__);
}

#pragma mark -- Send Support Request
- (void)setSupported:(BOOL)spt{
    if(spt)
    [[AVOSManger sharedManger] supportVideoId:self.videoPlayer.v_id completion:^(NSUInteger sptNum, BOOL succ) {
        if(succ)
        [self.supportLabel setText:[NSString stringWithFormat:@"%ld",sptNum]];
        else
            [TLAlertHelper showPopAlertWithString:@"点赞失败,请检查网络!"];
    }];
    else
        [[AVOSManger sharedManger] cancleVideoId:self.videoPlayer.v_id completion:^(NSUInteger sptNum, BOOL succ) {
            if(succ)
                [self.supportLabel setText:[NSString stringWithFormat:@"%ld",sptNum]];
            else
                [TLAlertHelper showPopAlertWithString:@"取消赞失败,请检查网络!"];
        }];
}

#pragma mark -- Caculate Height

- (CGFloat)caculateMainHeight{
    CGPoint convertPoint = [self.commentThumbTable convertPoint:CGPointZero toView:self];
    NSLog(@"caculate Main Height %@",NSStringFromCGPoint([self.commentThumbTable convertPoint:CGPointZero toView:self]));
    return convertPoint.y - 64;
}

- (IBAction)shareWXMmt:(id)sender {
    NSData *idData = [self.videoPlayer.v_id dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64StrId = [idData base64EncodedStringWithOptions:0];
    
    [AVOSManger valueForAVOSStaticType:AVOSDefautsTypeShareURI block:^(NSString *resp) {
        NSString *url = [NSString stringWithFormat:@"%@%@",resp,base64StrId];
        [[TLShareCenter center] shareWXMoment:url image:[self createShareImg] text:@"疯狂一刻" callBack:^(BOOL succ, NSDictionary *callBack, NSError *err) {
            if(succ)
            {
                [TLAlertHelper showSuccessHUDWithText:@"分享成功"];
            }
        }];

    }];
    

}

- (UIImage *)createShareImg{
    UIImage *image = [self.videoColumnImageView image];
    
    return image ? image : [UIImage imageNamed:Nav_Img_Logo];
}

@end
